package jaeger

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	us "net/url"
)

func jaegerTracesGluenets(url, guid string, containers []string, limit, start, end int64, data interface{}) error {
	var (
		err                               error
		serviceReq, operateReq, tracesReq *http.Response
		servicsName, operateName          []string
	)

	if serviceReq, err = http.Get(fmt.Sprintf(`http://%v/api/services`, url)); err != nil {
		return err
	}

	if servicsName, err = decodeServiceNames(serviceReq.Body); err != nil {
		return err
	}

	//fmt.Printf("\n\n %v \n ct: %v \n\n ", servicsName, containers)
	//fmt.Printf("%v", servicsName)

	for _, v := range servicsName {
		if operateReq, err = http.Get(fmt.Sprintf(`http://%v/api/services/%v/operations`, url, us.QueryEscape(v))); err != nil {
			return fmt.Errorf("request operate %v", err)
		}

		if operateName, err = decodeOperateNames(operateReq.Body); err != nil {
			return fmt.Errorf("decode operate %v", err)
		}

		//fmt.Printf("\n\n %v \n\n", operateName)

		for _, op := range operateName {
			for _, ct := range containers {
				u := fmt.Sprintf(`http://%v/api/traces?service=%v&start=%v&end=%v&limit=%v&operation=%v&tags=%%7B"hostname"%%3A"%v"%%7D`, url, us.QueryEscape(v), start, end, limit, us.QueryEscape(op), guid+"_"+ct)

				//fmt.Printf("\n\n url:  \v \n\n", u)
				if tracesReq, err = http.Get(u); err != nil {
					return fmt.Errorf("request jaeger %v", err)
				}
				bts, err := ioutil.ReadAll(tracesReq.Body)
				if err != nil {
					return fmt.Errorf("read trace body %v", err)
				}
				ts := make(map[string]interface{})
				if err = json.Unmarshal(bts, &ts); err != nil {
					return fmt.Errorf("decode trace %v", err)
				}

				for _, atr := range ts["data"].([]interface{}) {
					tid := atr.(map[string]interface{})["traceID"]
					spans := atr.(map[string]interface{})["spans"]
					drop := false
					//if tid == "00037201c75f5c7c" {
					//	fmt.Printf("\n\n span %v \n\n", spans)
					//}
					for _, sp := range spans.([]interface{}) {
						if sp.(map[string]interface{})["warnings"] != nil {
							drop = true
						}
					}
					if drop {
						continue
					}
					data.(map[string]interface{})[tid.(string)] = atr
				}
			}

			//fmt.Printf("\n\n%v\n\n", u)

			//*data.(*[]interface{}) = append(*data.(*[]interface{}), )
		}
	}

	return nil
}
